package com.example.mybatis.utils;

import com.example.mybatis.model.ColumnInfo;
import com.example.mybatis.model.SheetInfo;
import com.sun.org.apache.xml.internal.resolver.readers.SAXParserHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import java.util.HashMap;
import java.util.Map;

/**
 * SaxReader解析XML文档
 */
public class SaxDemoHandler extends SAXParserHandler {

    private String workBookName;

    private Map<String, SheetInfo> sheetInfoMap;

    private String sheetName;

    private static Logger logger = LoggerFactory.getLogger(SaxDemoHandler.class);

    @Override
    public void startDocument() throws SAXException {
        //开始解析文档
        super.startDocument();
        logger.info("----开始解析文档----");
        sheetInfoMap = new HashMap<>();

    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        super.startElement(namespaceURI, localName, qName, atts);
        logger.info("namespaceURI={},localName={},qName={}",namespaceURI,localName,qName);
        if(qName.equals("workbook")){
            String workBookName = atts.getValue("name");
            this.workBookName = workBookName;
        }
        if(qName.equals("sheet")){
            String sheetName = atts.getValue("name");
            this.sheetName = sheetName;
            String voClass = atts.getValue("voClass");
            SheetInfo sheetInfo = new SheetInfo(sheetName,voClass);
            sheetInfoMap.put(sheetName,sheetInfo);
        }
        if(qName.equals("column")){
            String columnName = atts.getValue("name");
            String displayName = atts.getValue("displayName");
            String type = atts.getValue("type");
            Integer width = Integer.valueOf(atts.getValue("width"));
            ColumnInfo columnInfo = new ColumnInfo(columnName,displayName,type,width);
            sheetInfoMap.get(this.sheetName).getColumns().add(columnInfo);
        }

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String characters = new String(ch,start,length);
        logger.info("characters={}",characters);
    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        super.endElement(namespaceURI, localName, qName);
        logger.info("---解析{}元素结束",qName);
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        logger.info("---结束解析文档---");
    }

    public String getWorkBookName() {
        return workBookName;
    }

    public Map<String, SheetInfo> getSheetInfoMap() {
        return sheetInfoMap;
    }


}
